package com.csi.service.impl;
import com.csi.domain.User;
import com.csi.domain.UserAssess;
import com.csi.mapper.UserInfoMapper;
import com.csi.service.UserService;
import com.csi.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserInfoMapper userInfoMapper;

    /**
     * 用户登录
     *
     * @param userNickname
     * @param password
     * @return
     */
    @Override
    public User login(String userNickname, String password) {
        password = MD5Utils.getMD5String(password);
        System.out.println("password = " + password);
        return userInfoMapper.login(userNickname, password);
    }

    /**
     * 用户注册
     *
     * @param user
     * @return
     */
    @Override
    public int register(User user) {
        user.setUserPassword(MD5Utils.getMD5String(user.getUserPassword()));
        return userInfoMapper.register(user);
    }

    /**
     * 根据用户id查找用户信息
     *
     * @param id 用户id
     * @return 用户信息
     */
    @Override
    @Transactional
    public User findById(long id) {
        return userInfoMapper.findById(id);
    }

    @Override
    public int updateUser(User user) {
        return userInfoMapper.updateUser(user);
    }

    /**
     * 根据用户查找用户密码
     * @param id 用户id
     * @return 执行结果
     */
    @Override
    public User findByIdAndPassword(long id) {
        return userInfoMapper.findByIdAndPassword(id);
    }

    /**
     * 修改用户密码
     * @param id 用户id
     * @param oldPassword 旧密码
     * @param newPassword 新密码
     * @return 执行结果
     */
    @Override
    public int changePassword(long id, String oldPassword, String newPassword) {
        oldPassword = MD5Utils.getMD5String(oldPassword);
        newPassword = MD5Utils.getMD5String(newPassword);
        User user = userInfoMapper.findById(id);
//        检查原密码是否正确
        if(user.getUserPassword().equals(oldPassword)) {
            user.setUserPassword(newPassword);
        }
        return userInfoMapper.updatePassword(id,oldPassword,newPassword);
    }

    /**
     * 根据用户id查找用户评价
     * @param userId 用户ID
     * @return 执行结果
     */
    @Override
    public List<UserAssess> getUserAssessByUserId(long userId) {
        return userInfoMapper.getUserAssessByUserId(userId);
    }

    @Override
    public List<User> getUsersByHotelId(long hotelId) {
        return userInfoMapper.getUsersByHotelId(hotelId);
    }

}
